import { action, computed, makeObservable, observable, flow, autorun } from 'mobx'
import axios from 'axios'
class CounterStore {
  count = 0
  users = []
  username = ''
  constructor() {
    makeObservable(this, {
      count: observable,
      users: observable,
      username: observable,
      getResult: computed,
      increment: action.bound,
      decrement: action.bound,
      getData: action.bound,
      changeUsername: action.bound
    })

    autorun(async () => {
      try {
        await uniqueUsername(this.username)
        console.log('username', this.username)
      } catch (error) {
        console.log(error)
      }
    }, {
      delay: 1000
    })
  }

  get getResult() {
    return this.count * 10
  }

  increment() {
    this.count += 1
  }
  decrement() {
    this.count -= 1
  }

  getData = flow(function* () {
    const { data } = yield axios.get('https://api.github.com/users')
    this.users = data
  })

  changeUsername(username) {
    this.username = username
  }
}

function uniqueUsername(username) {
  return new Promise((resolve, reject) => {
    if (username === 'admin') {
      reject('不能输入admin')
    } else {
      resolve()
    }
  })
}

const counter = new CounterStore()

export default counter
